import request from '@/utils/request'
import _path from 'path'
import { useUserStore } from '@/stores/user'

export const dataApi = {
  // 获取记录列表
  async getRecords(params) {
    try {
      const response = await request({
        url: '/api/data/list',
        method: 'get',
        params: {
          page: params.page || 1,
          pageSize: params.pageSize || 10,
          type: params.type || '',
          status: params.status || '',
          keyword: params.keyword || '',
          start_date: params.start_date,
          end_date: params.end_date
        }
      })
      return response
    } catch (error) {
      console.error('获取记录列表失败:', error)
      throw error
    }
  },

  // 获取可选字段列表
  async getAvailableFields() {
    try {
      const response = await request({
        url: '/api/data/available-fields',
        method: 'get'
      })
      return response
    } catch (error) {
      console.error('获取可选字段失败:', error)
      throw error
    }
  },

  // 下载导入模板
  async downloadTemplate(data) {
    try {
      const userStore = useUserStore()
      // 使用fetch API
      const response = await fetch('/api/data/template', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${userStore.token}`
        },
        body: JSON.stringify(data)
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.message || '下载失败')
      }

      // 获取blob数据
      const blob = await response.blob()
      
      // 使用showSaveFilePicker API
      try {
        const handle = await window.showSaveFilePicker({
          suggestedName: 'import_template.xlsx',
          types: [{
            description: 'Excel 文件',
            accept: {
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx']
            }
          }]
        })
        const writable = await handle.createWritable()
        await writable.write(blob)
        await writable.close()
        return { success: true }
      } catch (error) {
        if (error.name === 'AbortError') {
          // 用户取消了保存操作
          return { success: false, canceled: true }
        }
        throw error
      }
    } catch (error) {
      console.error('下载模板失败:', error)
      throw error
    }
  },

  // 预览导入数据
  async previewImport(file) {
    const formData = new FormData()
    formData.append('file', file)
    
    return request({
        url: '/api/data/preview',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
  },

  // 导入数据
  async importData(formData) {
    const response = await request({
      url: '/api/data/import',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response
  },

  // 导出数据
  async exportData(params) {
    let tempFilePath = null
    try {
      // 确保fields参数正确传递
      const exportParams = {
        ...params,
        fields: params.fields ? JSON.stringify(params.fields) : undefined,
        format: params.format || 'xlsx'
      }

      console.log('导出参数:', exportParams)

      const queryString = Object.entries(exportParams)
        .filter(([_, value]) => value !== undefined && value !== null)
        .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
        .join('&')
      
      const response = await request({
        url: `/api/data/export?${queryString}`,
        method: 'get'
      })

      console.log('导出响应:', response.data)

      // 检查响应格式
      if (!response.data?.fileName || !response.data?.downloadUrl) {
        console.error('导出失败，响应数据:', response.data)
        throw new Error('导出失败：' + (response.data?.message || '服务器返回错误'))
      }

      const { downloadUrl, tempFilePath: filePath } = response.data
      tempFilePath = filePath

      // 下载文件
      const downloadResponse = await request({
        url: downloadUrl,
        method: 'get',
        responseType: 'blob'
      })

      // 根据format设置正确的MIME类型和文件扩展名
      const isCSV = params.format && params.format.toLowerCase() === 'csv'
      const mimeType = isCSV ? 'text/csv' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const fileExt = isCSV ? '.csv' : '.xlsx'

      const blob = new Blob([downloadResponse.data], { type: mimeType })
      
      try {
        const handle = await window.showSaveFilePicker({
          suggestedName: response.data.fileName,
          types: [{
            description: isCSV ? 'CSV 文件' : 'Excel 文件',
            accept: {
              [mimeType]: [fileExt]
            }
          }]
        })
        const writable = await handle.createWritable()
        await writable.write(blob)
        await writable.close()

        return { success: true }
      } catch (error) {
        if (error.name === 'AbortError') {
          // 用户取消了保存操作，清理临时文件
          if (tempFilePath) {
            await request({
              url: '/api/data/clean-temp-file',
              method: 'post',
              data: { filePath: tempFilePath }
            }).catch(console.error)
          }
          return { success: false, canceled: true }
        }
        throw error
      }
    } catch (error) {
      // 如果出错，清理临时文件
      if (tempFilePath) {
        await request({
          url: '/api/data/clean-temp-file',
          method: 'post',
          data: { filePath: tempFilePath }
        }).catch(console.error)
      }

      console.error('导出数据失败:', error)
      throw error
    }
  },

  // 下载文件
  async downloadFile(id) {
    try {
      return await request({
        url: `/api/data/download/${id}`,
        method: 'get',
        responseType: 'blob'
      })
    } catch (error) {
      console.error('下载文件失败:', error)
      throw error
    }
  },

  // 批量删除记录
  async batchDelete(ids) {
    try {
      return await request({
        url: '/api/data/batch-delete',
        method: 'post',
        data: { ids }
      })
    } catch (error) {
      console.error('批量删除记录失败:', error)
      throw error
    }
  },

  // 记录操作日志
  async logOperation(data) {
    // 后端已在各个控制器中处理日志记录，此处不再需要单独调用
    return { success: true };
  },

  // 下载记录文件
  async downloadRecordFile(id) {
    try {
      // 先获取记录信息
      const response = await request({
        url: `/api/data/list`,
        method: 'get',
        params: {
          id: id,
          pageSize: 1
        }
      })

      console.log('获取到的记录信息:', response)

      if (!response || !response.items || !response.items[0]) {
        console.error('记录不存在:', { id, response })
        throw new Error('记录不存在')
      }

      const record = response.items[0]
      console.log('记录详情:', record)

      // 根据记录类型构造下载URL
      const downloadUrl = record.type === '导出'
        ? `/api/data/download/exports/${record.file_name}`
        : `/api/data/download/imports/${record.file_name}`
      console.log('下载URL:', { id, downloadUrl })

      // 下载文件
      const downloadResponse = await request({
        url: downloadUrl,
        method: 'get',
        responseType: 'blob'
      })

      // 从响应头中获取文件名和MIME类型
      const contentDisposition = downloadResponse.headers['content-disposition']
      const contentType = downloadResponse.headers['content-type']
      
      // 解析文件名，如果没有则使用记录中的文件名
      const fileName = contentDisposition
        ? decodeURIComponent(contentDisposition.split('filename*=UTF-8\'\'')[1])
        : record.file_name

      const blob = new Blob([downloadResponse.data], { type: contentType })
      
      try {
        // 使用 showSaveFilePicker API 让用户选择保存位置
        const handle = await window.showSaveFilePicker({
          suggestedName: fileName,
          types: [{
            description: 'Excel 文件',
            accept: {
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
              'application/vnd.ms-excel': ['.xls'],
              'text/csv': ['.csv']
            }
          }]
        })
        const writable = await handle.createWritable()
        await writable.write(blob)
        await writable.close()
        
        return { success: true }
      } catch (error) {
        if (error.name === 'AbortError') {
          // 用户取消了保存操作
          return { success: false, canceled: true }
        }
        throw error
      }
    } catch (error) {
      console.error('下载记录文件失败:', error)
      throw error
    }
  },

  // 根据MIME类型获取文件扩展名
  getFileExtension(mimeType) {
    const mimeToExt = {
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
      'application/vnd.ms-excel': '.xls',
      'text/csv': '.csv'
    }
    return mimeToExt[mimeType] || '.xlsx'
  },

  // 删除单条记录
  async deleteRecord(id) {
    try {
      return await request({
        url: `/api/data/record/${id}`,
        method: 'delete'
      })
    } catch (error) {
      console.error('删除记录失败:', error)
      throw error
    }
  },

  // 清理临时文件
  cleanupTempFile(filePath) {
    return request({
      url: '/api/data/clean-temp-file',
      method: 'post',
      data: { filePath }
    })
  },

  // 设置日志保留天数
  async setRetentionDays(days) {
    try {
      const response = await request({
        url: '/api/data/retention-days',
        method: 'post',
        data: { days }
      })
      return response
    } catch (error) {
      console.error('设置日志保留天数失败:', error)
      throw error
    }
  },

  // 获取日志保留天数
  async getRetentionDays() {
    try {
      const response = await request({
        url: '/api/data/retention-days',
        method: 'get'
      })
      return response
    } catch (error) {
      console.error('获取日志保留天数失败:', error)
      throw error
    }
  }
} 